package com.samnative.pineapple.main;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

import com.shashank.sony.fancytoastlib.FancyToast;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.utils.MD5Util;
import com.samnative.pineapple.utils.TimeCount;
import com.samnative.pineapple.value.Config;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import ezy.ui.view.RoundButton;


public class SetMobileActivity extends BaseActivity implements OnClickListener, TimeCount.ITimeCountListener {

    /**
     * 输入手机号
     */
    private EditText etPhone;
    /**
     * 输入验证码
     */
    private EditText etVerifycode;

    /**
     * 获取验证码按钮
     */
    private RoundButton btnVerifyCode;
    /**
     * 提交确定按钮
     */
    private RoundButton confirmBtn;
    /**
     * 定时间器
     */
    private TimeCount mTimeCount;
    private String mobile, code;
    private String encrypt = "";


    @Override
    protected int getLayoutId() {
        return R.layout.activity_set_mobile;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        encrypt = getIntent().getStringExtra("encrypt");
        mTimeCount = new TimeCount(60000, 1000);
        mTimeCount.setTimerCountListener(this);
        findViewById(R.id.iv_back).setOnClickListener(this);
        confirmBtn = findViewById(R.id.confirm_btn);
        etPhone = (EditText) findViewById(R.id.et_phone);
        etVerifycode = (EditText) findViewById(R.id.et_verifycode);
        btnVerifyCode = findViewById(R.id.tv_get_verity);
        btnVerifyCode.setOnClickListener(this);
        confirmBtn.setOnClickListener(this);
    }

    protected void initData() {
        mTimeCount = new TimeCount(60000, 1000);
        mTimeCount.setTimerCountListener(this);
    }


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_get_verity:
                if (etPhone.getText().toString().isEmpty()) {
                    FancyToast.showToast(mContext, "手机号码不能为空!", FancyToast.WARNING, false);
                } else if (etPhone.getText().toString().length() < 5) {
                    FancyToast.showToast(mContext, "请输入正确的手机号码!", FancyToast.WARNING, false);
                } else {
                    mobile = etPhone.getText().toString();
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
                    map.put("username", AppPrefer.getUserModel(mContext).getData().getUsername());
                    map.put("mobile", mobile);
                    map.put("countrycode", "");
                    map.put("devicenumber", Config._uuid);
                    map.put("privatekey", MD5Util.getMD5Str(mobile + Config._API_KEY));
                    map.put("sendType", "update_phone_");
                    map.put("_apiname", "user.public.sendvalicode");
                    HttpRequest.post(this, "", map, new JsonResult() {
                        @Override
                        public void reqestSuccess(JSONObject result) {
                            // TODO Auto-generated method stub
                            mTimeCount.start();
                            btnVerifyCode.setEnabled(false);
                            FancyToast.showToast(mContext, getString(R.string.verify_send_success), FancyToast.INFO, false);
                        }

                        @Override
                        public void requestFailure(int code, String msg) {
                            super.requestFailure(code, msg);
                        }
                    });
                }
                break;
            case R.id.confirm_btn:
                if (etPhone.getText().toString().isEmpty()) {
                    FancyToast.showToast(mContext, "手机号码不能为空!", FancyToast.WARNING, false);
                } else if (etVerifycode.getText().toString().isEmpty()) {
                    FancyToast.showToast(mContext, "验证码不能为空!", FancyToast.WARNING, false);
                } else {
                    code = etVerifycode.getText().toString();
                    Map<String, String> map = new HashMap<>();
                    map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
                    map.put("mobile", etPhone.getText().toString().trim());
                    map.put("encrypt", encrypt);
                    map.put("sourcetype", "1");
                    map.put("valicode", MD5Util.getMD5Str(etVerifycode.getText().toString().trim() + Config._API_KEY));
                    map.put("countrycode", "");
                    map.put("_apiname", "user.user.updatemobile");
                    HttpRequest.post(this, "", map, new JsonResult() {
                        @Override
                        public void reqestSuccess(JSONObject result) {
                            // TODO Auto-generated method stub
                            FancyToast.showToast(mContext, "修改成功!", FancyToast.SUCCESS, false);
                            showUserInfo();
                        }

                        @Override
                        public void requestFailure(int code, String msg) {
                            super.requestFailure(code, msg);
                        }
                    });
                }
                break;
            default:
                break;
        }
    }

    /**
     * 获取用户信息
     */
    private void showUserInfo() {
        Map<String, String> map = new HashMap<>();
        map.put("_apiname", "user.index.main");
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));

        HttpRequest.post(SetMobileActivity.this, null, map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                // TODO Auto-generated method stub
                try {
                    AppPrefer.getInstance(mContext).put(AppPrefer.userinfo, result.toString());

                    if (PasswordLoginVerityActivity.instance != null) {
                        PasswordLoginVerityActivity.instance.finish();
                    }

                    finish();
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }

            @Override
            public void requestFailure(int code, String msg) {
                super.requestFailure(code, msg);
            }
        });
    }


    // ==============================================计时器监听 START
    @Override
    public void onTick(long millisUntilFinished) {
        // TODO Auto-generated method stub
        btnVerifyCode.setText((millisUntilFinished / 1000) + getString(R.string.verify_confirm));
        btnVerifyCode.setEnabled(false);
    }

    @Override
    public void onFinish() {
        // TODO Auto-generated method stub
        btnVerifyCode.setText(getString(R.string.verify_send_again));
        btnVerifyCode.setEnabled(true);
    }

    // ==============================================计时器监听 END

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
